import {
  VuexModule,
  Module,
  Action,
  Mutation,
  getModule,
} from 'vuex-module-decorators';
// import { login, logout, getInfo, loginWechat } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/cookies';
import store from '@/store';

export interface IUserState {
  token: string;
  name: string;
  avatar: string;
  introduction: string;
  roles: string[];
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public token = getToken() || '';
  public name = '';
  public avatar = '';
  public introduction = '';
  public roles: string[] = [];

  @Action
  public async Login() {
    const token = 'admin-token';
    setToken(token);
    this.SET_TOKEN(token);
    this.SET_ROLES();
  }

  @Action
  public ResetToken() {
    removeToken();
    this.SET_TOKEN('');
  }

  @Action
  public async LogOut() {
    if (this.token === '') {
      throw Error('LogOut: token is undefined!');
    }

    removeToken();
    this.SET_TOKEN('');
  }
  @Action
  public async GetUserInfo() {
    if (this.token === '') {
      throw Error('GetUserInfo: token is undefined!');
    }
    const role = 'admin'; // 正式从接口获取

    if (!role) {
      throw Error('Verification failed, please Login again.');
    }

    // roles must be a non-empty array
    if (!role || role.length <= 0) {
      throw Error('GetUserInfo: roles must be a non-null array!');
    }
    this.SET_ROLES();
  }

  @Mutation
  private SET_ROLES() {
    this.roles.push('admin');
  }

  @Mutation
  private SET_TOKEN(token: string) {
    this.token = token;
  }
}

export const UserModule = getModule(User);

// 2019年夏，陪伴了一整个暑假的她，失踪在某个酷热的艳阳天，再也未曾见到。
